package com.qf.service.impl;


import com.qf.dao.ReturnDao;
import com.qf.dao.impl.ReturnDaoImpl;
import com.qf.entity.BooksBorrow;
import com.qf.service.ReturnService;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

public class ReturnServiceImpl implements ReturnService {
    ReturnDao returnDao=new ReturnDaoImpl();
    @Override
    public int giveBackBook(Integer id, String name, String date,String illegal) throws ParseException {
        BooksBorrow b=null;
        StringBuffer sb=new StringBuffer();
        //查询单条借阅记录
        try {
            b = returnDao.selectBorrowBookByIdAndName(id, name);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //时间格式转换
        long returnStamp=0;
        long endStamp=0;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSSS");
        String dateTimeString = b.getEnd_date().format(formatter);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date return_date = sdf.parse(date);
            Date end_date=sdf.parse(dateTimeString);
            returnStamp = return_date.getTime();
            endStamp=end_date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //规定时间与还书时间比较
        if(endStamp<returnStamp){
            sb.append("已逾期"+ ((returnStamp-endStamp)/(1000*60*60*24)) +"天");
            illegal=sb.toString();
        }else{
            sb.append("/");
            illegal=sb.toString();
        }
        //执行还书
        try {
            return returnDao.giveBackBook(id,name,date,illegal);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public BooksBorrow selectBorrowBookByIdAndName(Integer id, String name) {
        //查询单条记录
        try {
            return returnDao.selectBorrowBookByIdAndName(id,name);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<BooksBorrow> selectBorrowBook() {
        try {
            return returnDao.selectBorrowBook();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
